import {Button,Mention,Timeline,Icon,message} from 'antd';
import {WeaRichText} from 'ecCom';
import './style/index.css';
import WfAt from "../../comp/wfat/index";
import * as FormUtil from "../../../util/formUtil";
const ButtonGroup = Button.Group;
import { inject, observer } from 'mobx-react';
import weaCube from 'weaCube';
const ReplyCom = weaCube.common.ReplyCom;

@inject('contractPageStore')
@observer
class Dynamic extends React.Component {
    constructor(props) {
		super(props);
        const {editorId,visible = false } = props;
        const {remark} = props;
        this.state={
            remark:remark,
            showRichText:true,
            dynamicKey:"all",
            visibleComponent: '',
            visible: false
        }

        if(!window.CK_REF){
			window.CK_REF = {};
		}
    }
  

    componentWillReceiveProps(nextProps) {
		//转发
		const {editorId,visible = false ,isClear = false} = nextProps;

		
		if(isClear && !this.props.isClear){
			this.setState({
				remark:'',
				signdocids:'',
				signdocreplacedata:[],
				signworkflowids:'',
				signworkflowreplacedata:[],
				annexdocids:'',
				annexdocinfos:[],
				remarkLocation:''
			});
		}
	}

    shouldComponentUpdate(nextProps, nextState) {
		return 	this.state.remark !== nextState.remark||
				this.state.signdocids !== nextState.signdocids||
				this.state.signworkflowids !== nextState.signworkflowids||
				this.state.annexdocinfos !== nextState.annexdocinfos||
				this.state.remarkLocation !== nextState.remarkLocation||
				this.state.visibleComponent !== nextState.visibleComponent||
				this.state.hasInitListUploadComponent !== nextState.hasInitListUploadComponent||
				this.props.isShowSignInput !== nextProps.isShowSignInput||
				this.props.visible !== nextProps.visible;
	}

    componentDidUpdate(){
    	const {visible = false} = this.props;

		if(visible){			
            const ckeditorid  = this.refs.WeaRichText.editor.container.getId();
            console.log('ckeditorid',ckeditorid);
			this.initAutoAt($(`#${ckeditorid}`).find('iframe')[0]);
		}
	}
    
    componentDidMount(){
    	const {markInfo,editorId} = this.props;
    	// const {isannexupload_edit = '',annexsecId = ''} = markInfo;
		// if(isannexupload_edit === '1'){
		// 	//未设置附件上传目录
		// 	if (trim(annexsecId).length === 0 ||  annexsecId  <= 0){
		// 			message.warning('请设置签字意见附件上传目录！',5);
		// 	}
		// }
		window.CK_REF[editorId] = this.refs.WeaRichText;
    }


    showComponent(componet){
		this.setState({visibleComponent:componet});		
    }
    
    initAutoAt(ifr){
        console.log('ifr',ifr);
		const {editorId} = this.props;
		const _this  = this;
		const ckeditor = this.refs.WeaRichText;
		try {
			let datas = window.__atdata;
			if (window.__atdataready != true || !!!datas) {
				setTimeout(function () {
					_this.initAutoAt(ifr);
				}, 1000);
				return ;
			}
			
			let allatids = ",";
	        let names = jQuery.map(datas, function(value, i) {
	        	if (allatids.indexOf("," + value.uid + ",") == -1) { 
		        	allatids += value.uid + ",";
		            return {'id':value.uid,'name':value.data, 'py':value.datapy};
	            }
	        });
		    let at_config = {
		        at: "@",
		        data: names,
		        tpl: "<li data-value='@${name}'>${name}</li>",
		        insert_tpl: "<a href='/hrm/HrmTab.jsp?_fromURL=HrmResource&id=${id}' atsome='@${id}' contenteditable='false' style='cursor:pointer;text-decoration:none !important;margin-right:8px;color:#2777c1!important;' target='_blank'>${atwho-data-value}</a>", 
		        limit: 100,
		        show_the_at: true,
		        start_with_space : false,
		        with_repeat_matcher : false,
		        search_key_py : 'py',
		        ckeditor:ckeditor,
		        editorId:editorId
		    }
			let ifrBody = ifr.contentDocument.body;
		    jQuery(ifrBody).atwho('setIframe', ifr).atwho(at_config);
		    let atwhoblockobj = jQuery(".atwho-view");
		    atwhoblockobj.perfectScrollbar({horizrailenabled:false,zindex:11111});
	    } catch (e) {console.log(e)}
    }
    
	render() {
        const {Card} = this.props.contractPageStore;

        const {isShowSignInput=false,editorId,ls=false,ckConfig={},maxHeight=0} = this.props;
        let  {remark = ''} = this.state;
        const {visibleComponent=''} = this.state;

        ckConfig.toolbar = [
            { name: 'document', items: [ 'Source'] },
            { name: 'basicstyles', items: [ 'Bold', 'Italic', 'Underline', 'Strike', ] },
            { name: 'styles', items: [ 'Font', 'FontSize' ] },
            { name: 'colors', items: [ 'TextColor','BGColor' ] },
            { name: 'paragraph', items: [ 'NumberedList', 'BulletedList', '-', 'Outdent', 'Indent','-','JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'] },
            { name: 'links', items: [ 'Link', 'Unlink' ] },
            { name: 'tools', items: [ 'Maximize' ] },
            { name: 'insert', items: [ 'Table', '-', 'Undo', 'Redo'] }
        ];
                                        
        ckConfig.extraPlugins = 'autogrow'; 			
        ckConfig.height = 70;			        
        ckConfig['autoGrow_minHeight'] = 70;
        if(maxHeight > 0) ckConfig['autoGrow_maxHeight'] = maxHeight;
        ckConfig.removePlugins  = 'resize';
        ckConfig.uploadUrl = '/api/doc/upload/uploadFile';
        ckConfig.fontSize_sizes = '8/8px;9/9px;10/10px;11/11px;12/12px;14/14px;16/16px;18/18px;20/20px;22/22px;24/24px;26/26px;28/28px;36/36px;';
        ckConfig.startupFocus = false;
        const ckprops  = {
            id:editorId,
            ref:editorId,
            ls:ls,
            ckConfig:ckConfig,
            value:remark,
            scrollContainer:'.wea-new-top-req-content'
        };


        
        // 顶部，底部工具栏扩展
        const extentsConfig = [
           
            {
                name:'Upload',
                type:'image',
                show: <div className="wea-cb-item">
                        <span className={`wea-cbi-icon cke_button_icon cke_button__image_icon`} />
                     </div>,
                uploadUrl:'/api/doc/upload/uploadFile',
                category:'all',
                limitType:'jpg,gif,png',
                title:'上传图片',
                needLoading:false
            },
            {
                name:'Component',
                show:<WfAt editorId={editorId} appendHtmlToCKEditor={this.addAtInfo.bind(this)} visible={visibleComponent === 'WfAt'} showComponent={this.showComponent.bind(this)}/>
            },
            // {
            // name: 'Upload', // 上传组件
            // type: 'file', // 上传组件类型
            // show: <Icon type='paper-clip' title='上传附件' />, // 使用 antd 图标
            // uploadUrl: '/api/doc/upload/uploadFile?model=reply', // 上传地址
            // category: '/api/doc/upload/uploadFile?model=reply', // 文档目录
            // },
            // {
            // name: 'Browser', // 浏览按钮组件
            // show: <i className='icon-coms-Journal' title='文档' />, // 使用组件库图标
            // type: '37', // 浏览按钮类型 文档
            // title: '文档', // 浏览按钮标题
            // },
            // {
            // name: 'Browser', // 浏览按钮组件
            // show: <i className='icon-coms-Workflow-o' title='流程' />,
            // type: '152', // 浏览按钮类型
            // title: '流程', //浏览按钮标题
            // },
        ];
        // const Com = () => (
        //     <Button type={'primary'} onClick={()=>{}}>发布</Button>
        //   );
        // 顶部，底部工具栏扩展
        const bottomBarConfig = [
            // {
            // name: 'Component', // 自定义组件
            // show: <Com />,
            // },
            {
            name: 'Upload', // 上传组件
            type: 'list', // 上传组件类型
            show: <span style={{ fontSize: 12 }}>
                <Icon type='paper-clip' title='上传附件' /> 附件</span>, // 使用 antd 图标
            uploadUrl: '/api/doc/upload/uploadFile?model=reply', // 上传地址
            category: '/api/doc/upload/uploadFile?model=reply', // 文档目录
            onListChange: (ids, list) => console.log('ids, list: ', ids, list),
            },
            {
            name: 'Browser', // 浏览按钮组件
            show: <span style={{ fontSize: 12 }}>
                <i className='icon-coms-Journal' title='文档' /> 文档</span>, // 使用组件库图标
            type: '37', // 浏览按钮类型 文档
            title: '文档', // 浏览按钮标题
            },
            {
            name: 'Browser', // 浏览按钮组件
            show: <span style={{ fontSize: 12 }}>
                <i className='icon-coms-Workflow-o' title='流程' /> 流程</span>,
            type: '152', // 浏览按钮类型
            title: '流程', // 浏览按钮标题
            },
        ];

        let bottomBarRight = {
            // width: 155,
            Component: [
                <span className="wea-rich-text-toolbar-bottom-item" style={{position: "relative"}}>
                    <Button className="wea-button-release" onClick={()=>this.onPublicComment()}>
                        <span><span className="icon-coms-Release" /><span>发布</span></span>
                    </Button>
                    {/* <Button onClick={()=>{}} style={{marginLeft: '8px'}}>取消</Button> */}
                </span>
            ]
        };

      
		return (
            <div className={"coms-mode-docker"} style={{height:'100%'}}>
                {Card.isInit&&Card.reply &&<ReplyCom reply={Card.reply} />}
            </div>
        );
    };

    doOnChangeEvent(value){
		this.setState({remark:value});
		this.props.onChange && this.props.onChange({remark:value},true);
	}

    doStatusChange(status){
		if(status === "ready"){
			const editor = this.refs.WeaRichText.getEditor();
			const ckeditorid  = this.refs.WeaRichText.editor.container.getId();
			const _this  = this;
			const {editorId} = this.props;
			// if(editorId === 'remark'){
	        //     $('#container').bind('click',function(e){
			// 		if($(e.target).parents('.wea-ckeditor-fileupload,.wf-ckeditor-wfat,.wf-ckeditor-wfphrase').length <= 0){
	        //             _this.setState({visibleComponent:''});
			// 		}
			// 		const {remark }= _this.state;
			// 		const {actions} = _this.props;
			// 		if($(e.target).parents('#remark').length <= 0 && trim(remark).length === 0){
			// 			_this.props.actions && _this.props.actions.controlSignInput(false);
			// 		}
	        //     });
			// }
            
            if('remark' === editorId){
				$('.wea-req-forward-modal .ant-modal-content').bind('click',function(e){
					if($(e.target).parents('.wea-ckeditor-fileupload,.wf-ckeditor-wfat,.wf-ckeditor-wfphrase').length <= 0){
		                _this.setState({visibleComponent:''});
					}
				});
            }
            
            let i = 0 ;
            const el  = editor.document.$; 
            let timer = setInterval(()=>{
				$(el).off("click").on("click",function(e){
		    	    _this.setState({visibleComponent:''});
		    	});
		    	i++;
				if(i > 10){
					clearInterval(timer);
				}
			},500);
			
          	this.initAutoAt($(`#${ckeditorid}`).find('iframe')[0]);
		} 
	}

    addAtInfo(html){
		const instances  = false;
		let _html  = html;
		if(instances){
			const font  = instances.Font['_'].value||'微软雅黑';
			const fontsize  = instances.FontSize['_'].value||'12';
			_html = `<span style="font-family:'${font}';font-size:${fontsize}px;" >${html}</span>`;
        }
		this.appendHtmlToCKEditor(_html);
    }
    
    appendHtmlToCKEditor(html,pos){
		if(pos){
			this.refs.WeaRichText.insertHTML(FormUtil.convertSpecialChar(html),pos);
			const el  = this.refs.WeaRichText.getEditor().document.$;
			const _this  = this;
			$(el).off("click").on("click",function(e){
	    	    _this.setState({visibleComponent:''});
	    	});
		}else{
			this.refs.WeaRichText.insertHTML(FormUtil.convertSpecialChar(html));
		}
    }
    

    buttonBtnChange(name = '', ids = '', list = [], type = '',addfileid=''){
		let returnInfo = [];
		let changedatas = {};
		if(name === 'Browser'){
			//const requestid  = WfForm.getReqState().getIn(['params','requestid']);
			//const userid  = WfForm.getReqState().getIn(['params','f_weaver_belongto_userid']);
			const {requestid = -1 ,userid = -1} = this.props;
			if(type === 37){
				changedatas.signdocids = ids;
				changedatas.signdocreplacedata = list;
				this.setState(changedatas);
			}else if(type === 152){
				changedatas.signworkflowids = ids;
				changedatas.signworkflowreplacedata = list;
				this.setState(changedatas);
			}
			list.map(item=>{
				//unselectable='off' contenteditable='false'
				returnInfo.push(type === 37 ? 
					`<a href='/docs/docs/DocDsp.jsp?id=${item.id}&isrequest=1&requestid=${requestid}' unselectable='off' contenteditable='false'  target='_blank' title='${item.name}'   style=\"color:#2777c1;\" >${item.name}</a>&nbsp;&nbsp;`
					:
					`<a href='/workflow/request/ViewRequestForwardSPA.jsp?f_weaver_belongto_userid=${userid}&f_weaver_belongto_usertype=0&requestid=${item.id}&isrequest=1' unselectable='off' contenteditable='false'  target='_blank' style=\"color:#2777c1;\">${item.name}</a>&nbsp;&nbsp;`
				);
			});
		}else if(name === 'Upload'){
			if(type === 'file'){
				let _ids  = [];
				list.map(item=> {_ids.push(item.fileid)}); 
				changedatas['field-annexupload'] = _ids.join(',');	
				changedatas['annexdocinfos'] = list;
				if(addfileid){
					list.map(item=>{
						if(item.fileid === addfileid){
							returnInfo.push(`<a href='javascript:void(0);' onclick=\"parent.openFullWindowHaveBar('/docs/docs/DocDsp.jsp?id=${item.fileid}&isrequest=1&requestid=${requestid}&desrequestid=0')\" unselectable='off' contenteditable='false' style=\"color:#2777c1;\">${item.filename}</a>&nbsp;&nbsp;`);
						}
					});
				}else{
					this.setState({'field-annexupload':_ids,annexdocinfos:list,visibleComponent:'Upload',hasInitListUploadComponent:true});
				}
			}else{
				list.map(item => {
					const imglink  = `/weaver/weaver.file.FileDownload?fileid=${item.fileid}`;
					//returnInfo.push(`<img class='formImgPlay' src='${imglink}' data-imgsrc='${imglink}' onclick="window.imageCarousel(this)" alt=''/>`);
					returnInfo.push(`<img src='${imglink}' data-imgsrc='${imglink}' alt=''/>&#8203;`);
				});
//				this.appendHtmlToCKEditor(returnInfo.join(''));
//				const ckeditor  = this.refs.WeaRichText.getEditor();
//				ckeditor.setData(ckeditor.getData());
//				//this.refs.WeaRichText.focus('last');
//				this.refs.WeaRichText.insertHTML('','last');
				this.refs.WeaRichText.insertHTML(returnInfo.join(''));
				return " ";
			}
		}
		//this.props.onChange && this.props.onChange(changedatas);
		this.setState(changedatas);
		if(returnInfo.length > 0){
			this.appendHtmlToCKEditor(`<p>${returnInfo.join('')}</p>`,'last');
		}
		return " ";
	}
    
    onPublicComment=()=>{
        let {richText} = this.state;

        let ckref = this.refs['root_comment'];
        if(this.refs['root_comment'].wrappedInstance){
            ckref = this.refs['root_comment'].wrappedInstance;
        } 
        if (!ckref.checkMode()) {
            message.error("不能以源码模式或markdown模式保存，请将编辑器切换到可视化模式");
            return;
        }
        
        this.setState({richValue:richText});
        console.log('onPublicComment');
    }

    


    //动态评论切换
    onDynamicClick=(value)=>{
        var showRichText = true;
    	if(value=='dynamic'){
    		showRichText = false;
    	}

    	this.setState({
            showRichText:showRichText,
			dynamicKey:value 	
    	})
    }
    
}

export default Dynamic;